package com.bd.scm.module.user.controller;

import com.bd.offices.excel.ExcelUtil;
import com.bd.scm.domain.dto.user.PersonnelFilesDto;
import com.bd.scm.domain.models.user.PersonnelFiles;
import com.bd.scm.module.user.service.IPersonnelFilesService;
import com.bd.scm.module.utils.ResultUtil;
import com.bd.utils.FileUtil;
import com.bd.utils.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/employee")
@Api("人员档案接口")
public class PersonnelFilesController {

    @Autowired
    private IPersonnelFilesService personnelFilesService;

    @Value("${bd.upload.facePath}")
    private String facePath;

    /**
     * 获取人员信息.
     *
     * @param personnelFilesDto 条件
     * @return 导入人员日志信息集合
     */
    @PostMapping("list")
    @ApiOperation(value = "获取人员数据", httpMethod = "POST", protocols = "HTTP", notes = "获取人员数据", produces = "application/json")
    public Result getPersonList(@ApiParam(name = "personnelFilesDto", value = "人员档案实体类", required = true)
                                @RequestBody PersonnelFilesDto personnelFilesDto) {
        return ResultUtil.ok(personnelFilesService.getPersonList(personnelFilesDto));
    }

    /**
     * 离职
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/quitPerson")
    @ResponseBody
    @ApiOperation(value = "离职", httpMethod = "GET", protocols = "HTTP", notes = "离职", produces = "application/json")
    public Result quitPerson(@ApiParam(name = "personnelFilesDto", value = "人员档案实体类", required = true)
                             @RequestBody List<PersonnelFilesDto> personnelFilesDto) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        String flag = this.personnelFilesService.quitPerson(personnelFilesDto, clientIp);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 修改
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/updatePerson")
    @ResponseBody
    @ApiOperation(value = "修改", httpMethod = "GET", protocols = "HTTP", notes = "修改", produces = "application/json")
    public Result updatePerson(@ApiParam(name = "personnelFilesDto", value = "人员档案实体类", required = true)
                               @RequestBody PersonnelFilesDto personnelFilesDto, HttpServletRequest request) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        String flag = this.personnelFilesService.updatePerson(personnelFilesDto, clientIp);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 新增
     *
     * @param j 条件
     * @return
     */
//    @RequestMapping("/addPerson")
////    @ResponseBody
    @PostMapping("add")
    @ApiOperation(value = "新增", httpMethod = "POST", protocols = "HTTP", notes = "新增", produces = "application/json")
    public Result addPerson(@ApiParam(name = "personnelFilesDto", value = "人员档案实体类", required = true)
                            @RequestBody PersonnelFilesDto personnelFilesDto, HttpServletRequest request) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        String flag = this.personnelFilesService.addPerson(personnelFilesDto, clientIp);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 调动
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/transferPerson")
    @ResponseBody
    @ApiOperation(value = "新增", httpMethod = "GET", protocols = "HTTP", notes = "新增", produces = "application/json")
    public Result transferPerson(@ApiParam(name = "personnelFilesDto", value = "人员档案实体类", required = true)
                                 @RequestBody List<PersonnelFilesDto> personnelFilesDto, HttpServletRequest request) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        String flag = this.personnelFilesService.transferPerson(personnelFilesDto, clientIp);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 获取账户类型.
     *
     * @param
     * @return 账户类型信息
     */
    @RequestMapping("getacTypeList")
    @ResponseBody
    public Result getacTypeList() {
        return ResultUtil.ok(this.personnelFilesService.getacTypeList());
    }

    /**
     * 获取民族信息.
     *
     * @param
     * @return 民族信息
     */
    @RequestMapping("getNationList")
    @ResponseBody
    public Result getNation() {
        return ResultUtil.ok(this.personnelFilesService.getNation());
    }

    /**
     * 获取籍贯信息.
     *
     * @param
     * @return 籍贯信息
     */
    @RequestMapping("getNativeList")
    @ResponseBody
    public Result getNative() {
        return ResultUtil.ok(this.personnelFilesService.getNative());
    }

    /**
     * 获取档案类型
     */
    @RequestMapping("getUserType")
    @ResponseBody
    public Result getUserType() {
        return ResultUtil.ok(this.personnelFilesService.getUserType());
    }

    /**
     * 根据员工编号精确匹配
     *
     * @param personnelFilesDto 条件
     * @return 人员信息
     */
    @RequestMapping("getUserById")
    @ResponseBody
    public Result getUserById(@RequestBody PersonnelFilesDto personnelFilesDto) {
        return ResultUtil.ok(this.personnelFilesService.getUserById(personnelFilesDto));
    }

    /**
     * 获取人员编号
     */
    @RequestMapping("getUserSerial")
    @ResponseBody
    public Result getUserSerial() {
        return ResultUtil.ok(this.personnelFilesService.getUserSerialAndNo());
    }


    /**
     * 人员导出
     *
     * @param depSerial
     * @param serchTxt
     * @param response
     * @return
     * @throws IOException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "PersonnelFilesExport")
    @ApiOperation(value = "导出", httpMethod = "GET", protocols = "HTTP", notes = "导出", produces = "application/json")
    public Result PersonnelFilesExport(
            @ApiParam(name = "depSerial", value = "部门编号", required = true)
                    String depSerial,
            String serchTxt,
            HttpServletResponse response) throws IOException, InstantiationException, IllegalAccessException {
        PersonnelFilesDto personnelFilesDto = new PersonnelFilesDto();
        personnelFilesDto.setCurrent(new Long(-1));
        personnelFilesDto.setPageSize(new Long(-1));

        personnelFilesDto.setDepSerial(depSerial);
        personnelFilesDto.setSerchTxt(serchTxt);
        List<PersonnelFiles> doorDefinition = personnelFilesService.getPersonList(personnelFilesDto).getRecords();
        ExcelUtil.ExportExcel("导出人员名单" + UUID.randomUUID().toString(), response, doorDefinition, PersonnelFiles.class);
        return ResultUtil.ok();
    }

    /**
     * 导入
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("uploadingExcel")
    @ResponseBody
    public Result uploadingExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        //是否有错误信息
        String flag = this.personnelFilesService.uploadingExcel(file, request);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 下载模板
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/downLoadTemplate")
    public void downLoad(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "人员导入模板" + ".xlsx";
        ServletOutputStream out;
        FileUtil.setResponseHeader(fileName, response);
        String filePath = getClass().getResource("/downLoadTemplate/" + fileName).getPath();
        filePath = URLDecoder.decode(filePath, "UTF-8");
        FileInputStream inputstream = new FileInputStream(filePath);
        out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputstream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputstream.close();

        if (out != null) {
            out.flush();
            out.close();
        }
    }

    @PostMapping("/uploadFace")
    public String uploadFiles(HttpServletRequest request, int userId) {
        try {

            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

            for (MultipartFile file : files) {

                String fileName = System.currentTimeMillis() + file.getOriginalFilename();

                //String destFileName = req.getServletContext().getRealPath("") + "uploaded" + File.separator + fileName;
                String destFileName = facePath + File.separator + userId + File.separator + File.separator + fileName;


                File destFile = new File(destFileName);
                destFile.getParentFile().mkdirs();


                file.transferTo(destFile);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }

        return "showImg";
    }
}
